import { defineStore } from "pinia";
import { ref } from 'vue'
import request from '@/utils/request'
import { ElMessage } from "element-plus";
export const useFileStore = defineStore('fileStore',()=>{
    const fileSearch = ref({name:'',size:'',type:''})
    const pageInfo = ref({current:1,pageSize:5,total:0})
    const files = ref([])
    const ids = ref([])
    const getFiles = async ()=>{
        const {data:{records}} = await request.get('/file/page',{
            params:{
                current: pageInfo.value.current,
                pageSize: pageInfo.value.pageSize,
                name: fileSearch.value.name,
                size: fileSearch.value.size,
                type: fileSearch.value.type
            }
        })
        files.value = records.filter(item=>!item.isDelete)
        pageInfo.value.total = files.value.length
    }
    const refresh = ()=>{
        fileSearch.value = {name:'',size:'',type:''}
        getFiles()
    }
    const deleteFiles = async ()=>{
        const result = await request.delete('/file',{
            data: ids.value
        })
        result.code && result.code === 200?ElMessage.success('删除成功'):ElMessage.warning(result.msg)
        getFiles()
    }
    const handleSelectionChange = (val)=>{
        ids.value = val.map(item=>item.id)
    }
    const changeFileStatus = async (id,isdelete)=>{
        const file = files.value.filter(item=>item.id === id)[0]
        if(isdelete){
            console.log('isdelete')
            file.isDelete = !file.isDelete
        }
        const result = await request.put(`/file`,file)
        if(result.code === 200 && isdelete)ElMessage.success('删除成功')
        getFiles()
    }
    const handleUploadSuccess = ()=>{
        ElMessage.success('上传成功')
        getFiles()
    }
    const download = (id) =>{
        const url = files.value.filter(item=>item.id === id)[0].url
        window.open(url)
    }
    return {
        files,
        fileSearch,
        pageInfo,
        getFiles,
        refresh,
        deleteFiles,
        handleSelectionChange,
        changeFileStatus,
        handleUploadSuccess,
        download
    }
})